
package org.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
/*The search feature.
 * When the user wishes to search a partticular book, wither on the app database or on the web
 * this class is called. The items related to the search query are displayed to the user on UI
 * */
public class SearchBooksActivity extends Activity {
	private static String isbn1[] = new String[10];
	private EditText editText;
	private String searchText = "";
	private TextView textView1, textView2, textView3, textView4, textView5,
			textView6, textView7, textView8, textView9, textView10;
	private String Title[] = new String[10];
	private String Title_long[] = new String[10];
	private String Author[] = new String[10];
	private String Publisher[] = new String[10];
	private String Text[] = new String[10];
	private String isbn[] = new String[10];

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.searchbookslayout);

		editText = (EditText) findViewById(R.id.editText);
	}
	
	//The onclick method, called when the user selects "Search sfsu" button on the UI
	//If the particular book is available in the database then it fetches that book and tells 
	//the user that so and so user is selling this book
	public void onClick1(View view) throws Exception {

		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

		String line = "", s = "";

		String url = "http://isbndb.com/api/books.xml?access_key=GQIKRCH3&index1=title&value1="
				+ editText.getText();
		URL yahoo = new URL(url);
		URLConnection yc = yahoo.openConnection();
		BufferedReader in = new BufferedReader(new InputStreamReader(yc
				.getInputStream()));

		while ((line = in.readLine()) != null) {
			s += line;
		}

		System.out.println("XML: " + s + "\n");
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(s));

			Document doc = db.parse(is);
			NodeList nodes = doc.getElementsByTagName("BookData");
			System.out.println("\nBook Data length1: " + nodes.getLength()
					+ "\n");

			for (int i = 0; i < nodes.getLength(); i++) {
				Element element = (Element) nodes.item(i);

				NodeList title = element.getElementsByTagName("Title");
				Element line1 = (Element) title.item(0);

				Title[i] = getCharacterDataFromElement(line1);

				NodeList title_long = element.getElementsByTagName("TitleLong");
				line1 = (Element) title_long.item(0);

				Title_long[i] = getCharacterDataFromElement(line1);

				NodeList Author1 = element.getElementsByTagName("AuthorsText");
				line1 = (Element) Author1.item(0);

				Author[i] = getCharacterDataFromElement(line1);

				NodeList PublisherText = element
						.getElementsByTagName("PublisherText");
				line1 = (Element) PublisherText.item(0);

				Publisher[i] = getCharacterDataFromElement(line1);

				isbn1[i] = "0";
				Text[i] = "Title: " + Title[i] + "\n" + "Long Title: "
						+ Title_long[i] + "\n" + "Author: " + Author[i] + "\n"
						+ "Publisher: " + Publisher[i];
				isbn[i] = "0061031321";
				textView1 = (TextView) findViewById(R.id.TEXT_VIEW1);
				textView2 = (TextView) findViewById(R.id.TEXT_VIEW2);
				textView3 = (TextView) findViewById(R.id.TEXT_VIEW3);
				textView4 = (TextView) findViewById(R.id.TEXT_VIEW4);
				textView5 = (TextView) findViewById(R.id.TEXT_VIEW5);
				textView6 = (TextView) findViewById(R.id.TEXT_VIEW6);
				textView7 = (TextView) findViewById(R.id.TEXT_VIEW7);
				textView8 = (TextView) findViewById(R.id.TEXT_VIEW8);
				textView9 = (TextView) findViewById(R.id.TEXT_VIEW9);
				textView10 = (TextView) findViewById(R.id.TEXT_VIEW10);

				textView1.setText(Text[0]);
				textView2.setText(Text[1]);
				textView3.setText(Text[2]);
				textView4.setText(Text[3]);
				textView5.setText(Text[4]);
				textView6.setText(Text[5]);
				textView7.setText(Text[6]);
				textView8.setText(Text[7]);
				textView9.setText(Text[8]);
				textView10.setText(Text[9]);

			}

			isbn[1] = "9780804775540";
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	//The onclick method, called when the user selects "Search web" on the UI
	//All books that may have that keyword are fetched from the remote database 
	//called isbndb
	public void onClick2(View view) throws Exception {

		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

		searchText = editText.getText().toString();
		System.out.println("Value came------> " + searchText);

		String Text[] = new String[10];

		int cnt = 0;
		String result = "";
		System.out.println("Value came------> " + searchText);
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("Title", searchText));

		textView1 = (TextView) findViewById(R.id.TEXT_VIEW1);
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(
				"http://hci.cs.sfsu.edu/~fall2010.03/Includes/searchDatabaseWithKeywords.php");
		try {
			httppost.setEntity(new UrlEncodedFormEntity(postParameters));

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();

			result = sb.toString();
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
		}

		try {
			JSONArray jArray = new JSONArray(result);

			for (int i = 0; i < jArray.length(); i++) {
				JSONObject json_data = jArray.getJSONObject(i);
				Log.i("log_tag", " Title: " + json_data.getString("Title")
						+ ", Author: " + json_data.getString("Author")
						+ ", Publisher: " + json_data.getString("Publisher")
						+ ", Course Number: "
						+ json_data.getString("Course_Number") + ", ISBN: "
						+ json_data.getString("ISBN"));

				Text[cnt] = "Title: " + json_data.getString("Title") + "\n"
						+ "Author: " + json_data.getString("Author") + "\n"
						+ "Publisher: " + json_data.getString("Publisher")
						+ "\n" + "Course Number: "
						+ json_data.getString("Course_Number");
				isbn1[cnt] = json_data.getString("ISBN");
				cnt++;

				System.out.println("******ISBN: " + isbn1[0]);
			}

		} catch (JSONException e) { // Log.e("log_tag",
									// "Error parsing data "+e.toString());
			System.out.println("NO RECORDS FOUND1");
			System.out.println("Error got: " + e.getMessage());

			AlertDialog alertDialog = new AlertDialog.Builder(
					SearchBooksActivity.this).create();
			alertDialog.setTitle("No Records Found");
			alertDialog.setMessage("to try again press 'Try again'");

			alertDialog.setButton2("Try again",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {

							editText.setText(null);
						}
					});
			alertDialog.show();

		}

		textView2 = (TextView) findViewById(R.id.TEXT_VIEW2);
		textView3 = (TextView) findViewById(R.id.TEXT_VIEW3);
		textView4 = (TextView) findViewById(R.id.TEXT_VIEW4);
		textView5 = (TextView) findViewById(R.id.TEXT_VIEW5);
		textView6 = (TextView) findViewById(R.id.TEXT_VIEW6);
		textView7 = (TextView) findViewById(R.id.TEXT_VIEW7);
		textView8 = (TextView) findViewById(R.id.TEXT_VIEW8);
		textView9 = (TextView) findViewById(R.id.TEXT_VIEW9);
		textView10 = (TextView) findViewById(R.id.TEXT_VIEW10);

		textView1.setText(Text[0]);
		textView2.setText(Text[1]);
		textView3.setText(Text[2]);
		textView4.setText(Text[3]);
		textView5.setText(Text[4]);
		textView6.setText(Text[5]);
		textView7.setText(Text[6]);
		textView8.setText(Text[7]);
		textView9.setText(Text[8]);
		textView10.setText(Text[9]);

		System.out.println("*****************");

	}

	public static String getCharacterDataFromElement(Element e) {
		Node child = e.getFirstChild();
		if (child instanceof CharacterData) {
			CharacterData cd = (CharacterData) child;
			return cd.getData();
		}
		return "NOT FOUND";
	}

	//The onclick methods for books inside the list view.
	public void onClick3(View v) throws Exception {

		Intent i = new Intent(this,
				GetSingleBookAndStudentDetailsActivity.class);

		i.putExtra("ISBN", isbn1[0]);
		i.putExtra("CourseNumber", "dfghjklkjhgfhg");
		i.putExtra("CourseNumber1", "fghjkhgfddfghjk");
		i.putExtra("flag", "1");
		startActivity(i);

	}

	public void onClick4(View v) throws Exception {

		Intent i = new Intent(this,
				GetSingleBookAndStudentDetailsActivity.class);

		i.putExtra("ISBN", isbn1[1]);
		i.putExtra("CourseNumber", "dfghjklkjhgfhg");
		i.putExtra("CourseNumber1", "fghjkhgfddfghjk");
		i.putExtra("flag", "1");
		startActivity(i);

	}

	public void onClick5(View v) throws Exception {

		Intent i = new Intent(this,
				GetSingleBookAndStudentDetailsActivity.class);

		i.putExtra("ISBN", isbn1[2]);
		i.putExtra("CourseNumber", "dfghjklkjhgfhg");
		i.putExtra("CourseNumber1", "fghjkhgfddfghjk");
		i.putExtra("flag", "1");
		startActivity(i);

	}

	public void onClick6(View v) throws Exception {

		Intent i = new Intent(this,
				GetSingleBookAndStudentDetailsActivity.class);

		i.putExtra("ISBN", isbn1[3]);
		i.putExtra("CourseNumber", "dfghjklkjhgfhg");
		i.putExtra("CourseNumber1", "fghjkhgfddfghjk");
		i.putExtra("flag", "1");
		startActivity(i);

	}

	public void onClick7(View v) throws Exception {

		Intent i = new Intent(this,
				GetSingleBookAndStudentDetailsActivity.class);

		i.putExtra("ISBN", isbn1[4]);
		i.putExtra("CourseNumber", "dfghjklkjhgfhg");
		i.putExtra("CourseNumber1", "fghjkhgfddfghjk");
		i.putExtra("flag", "1");
		startActivity(i);

	}

	public void onClick8(View v) throws Exception {

		Intent i = new Intent(this,
				GetSingleBookAndStudentDetailsActivity.class);

		i.putExtra("ISBN", isbn1[5]);
		i.putExtra("CourseNumber", "dfghjklkjhgfhg");
		i.putExtra("CourseNumber1", "fghjkhgfddfghjk");
		i.putExtra("flag", "1");
		startActivity(i);

	}

	public void onClick9(View v) throws Exception {

		Intent i = new Intent(this,
				GetSingleBookAndStudentDetailsActivity.class);

		i.putExtra("ISBN", isbn1[6]);
		i.putExtra("CourseNumber", "dfghjklkjhgfhg");
		i.putExtra("CourseNumber1", "fghjkhgfddfghjk");
		i.putExtra("flag", "1");
		startActivity(i);

	}

	public void onClick10(View v) throws Exception {

		Intent i = new Intent(this,
				GetSingleBookAndStudentDetailsActivity.class);

		i.putExtra("ISBN", isbn1[7]);
		i.putExtra("CourseNumber", "dfghjklkjhgfhg");
		i.putExtra("CourseNumber1", "fghjkhgfddfghjk");
		i.putExtra("flag", "1");
		startActivity(i);

	}

	public void onClick11(View v) throws Exception {

		Intent i = new Intent(this,
				GetSingleBookAndStudentDetailsActivity.class);

		i.putExtra("ISBN", isbn1[8]);
		i.putExtra("CourseNumber", "Junk Text, No use");
		i.putExtra("CourseNumber1", "Junk Text, No use");
		i.putExtra("flag", "1");
		startActivity(i);

	}

	public void onClick12(View v) throws Exception {

		Intent i = new Intent(this,
				GetSingleBookAndStudentDetailsActivity.class);

		i.putExtra("ISBN", isbn1[9]);
		i.putExtra("CourseNumber", "dfghjklkjhgfhg");
		i.putExtra("CourseNumber1", "fghjkhgfddfghjk");
		i.putExtra("flag", "1");
		startActivity(i);

	}

}
